#ifndef _X7_H_INCLUDED_
#define _X7_H_INCLUDED_
#include <string>
using std::string;


class X7
{
private:
    int status = 0;
    const string X7_keywords = "data: $";
    const int MAX_RECV_SIZE = 1024;
    bool is_complete = false; 

    int protocolParser(const char* buffer,int size, int start)
    {
        if (status < 0){
            return -1;
        }       
        for(int i = start; i < size; i++){
            if(status == 6 && i < size-1){ 
                //协议解析已经完成，但是还有数据等待解析，说明不是本次发送的数据，直接返回进行后续业务流程
                is_complete = true;
                return i;
            }
            if(status != 5){
                if (buffer[i] == X7_keywords[status])
                    status += 1;
                else{
                    status = -1;
                    return -1;
                }
            }else{
                if(buffer[i] != '$'){
                    data += buffer[i];
                }
                else{
                    status += 1;
                }
            }
        }
        if(status == 6){
            is_complete = true;
        }
        return 0; 
    }

public:
    string data;
    X7() = default;

    int parser(const char* buffer, int size, int start)
    {
        return protocolParser(buffer, size, start);
    }
    
    //重设协议状态
    void reset(){
        data.clear();
        status = 0;
        is_complete = false;
    }

    bool isComplete(){
        return is_complete;
    }

    static string encoder(string& data);
};

inline string X7::encoder(string& data)
{
    string temp = "data:";
    temp += (data + "$");
    return temp;
}

#endif